package br.com.mynage.dao.impl;


import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;

import br.com.mynage.dao.IUsuarioDAO;
import br.com.mynage.dominio.Projeto;
import br.com.mynage.dominio.Usuario;
import br.com.mynage.exception.DaoException;



/**
 * Interface para a classes de Dao para usu�rio. 
 * @author sueltom
 *
 */
public class UsuarioDaoImpl extends GenericDaoImpl<Usuario> implements IUsuarioDAO  {

	@SuppressWarnings("unchecked")
	public Usuario buscarUsuario(String login, String senha) throws DaoException {
		EntityManager manager = getEntityManager();
		
		try{
			Session session = (Session) manager.getDelegate();
			
			Criteria criteria = session.createCriteria(Usuario.class);
			Criterion criterion = Restrictions.eq("login", login);
			criterion = Restrictions.and(criterion, Restrictions.eq("senha", senha));
			criteria.add(criterion);
			List<Usuario> lista = criteria.list();
			if(lista != null && lista.size() > 0){
				return lista.get(0);
			}
			return null;
		}catch (Exception e) {
			throw new DaoException();
		}finally{
			if(manager != null) manager.clear();
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<Usuario> findUsuariosByProjeto(Projeto projeto) throws DaoException {
		EntityManager manager = getEntityManager();
		List<Usuario> resul = new ArrayList<Usuario>();
		
		try {  
			
			Session session = (Session) manager.getDelegate();
			
			String sql = "SELECT id, nome, email FROM usuario u " +
					"inner join projeto_usuario p on p.id_usuario = u.id "+
					"WHERE p.id_projeto = " + projeto.getId();
			
			List<Object[]> rs = session.createSQLQuery(sql).list();
			
			for(Object o[]:rs) {
				int i = 0;
				Usuario u = new Usuario();
				u.setId((Integer)o[i++]);
				u.setNome((String)o[i++]);
				u.setEmail((String)o[i++]);
				resul.add(u);
			}

			return resul; 
		} catch (Exception e) {
			e.printStackTrace();
			throw new DaoException();
		} finally {
			if (manager != null) 
				manager.close(); 
		}
		
	}

	@Override
	public Class<Usuario> getClassType() {
		return Usuario.class;
	}

}
